package com.iot08.push.mob;

import com.alibaba.fastjson.JSONObject;
import com.iot08.common.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import mob.push.api.model.IosNotify;
import mob.push.api.model.Push;
import mob.push.api.model.PushMap;
import mob.push.api.model.PushFactoryExtra;
import mob.push.api.model.AndroidNotify;
import mob.push.api.model.PushForward;
import mob.push.api.model.PushTarget;
import mob.push.api.model.factory.HuaweiExtra;
import mob.push.api.model.factory.VivoExtra;
import mob.push.api.model.factory.XiaomiExtra;
import mob.push.api.utils.SetUtil;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @version 1.0
 * @Description:
 * @time: 2020/11/27 11:54
 * @author: Rock
 */
@Slf4j
public class MyPushWorkBuilder {
    public static final int TARGET_TAGS = 1;
    // 推送别名类型
    public static final int TARGET_ALIAS = 2;
    // 推送registrationId
    public static final int TARGET_RIDS = 4;

    private final Push push = new Push();

    public MyPushWorkBuilder() {
    }

    public Push build() {
        return push;
    }

    /**
     * @param content
     * @time: 2020/11/27 14:42
     * @author: Rock
     * @version 1.0
     */
    public void fillParams(String content, String scheme, String data, Integer platfrom, Integer iosProduction, Map<String, String> extraMap) {
        if (this.push.getPushTarget() == null) {
            this.push.setPushTarget(new PushTarget());
        }
        if (this.push.getPushForward() == null) {
            this.push.setPushForward(new PushForward());
        }
        this.push.getPushNotify().setContent(content);
        this.push.getPushNotify().setPlats(SetUtil.newSet(platfrom));
        if (new Integer(2).equals(platfrom)) {
            // iOS
            this.push.getPushNotify().setIosProduction(iosProduction);
            if (this.push.getPushNotify().getIosNotify() == null) {
                this.push.getPushNotify().setIosNotify(new IosNotify());
            }
            this.push.getPushNotify().getIosNotify().setMutableContent(1);
            this.push.getPushNotify().getIosNotify().setContentAvailable(1);
        } else {
            if (this.push.getPushNotify().getAndroidNotify() == null) {
                this.push.getPushNotify().setAndroidNotify(new AndroidNotify());
            }
            // 只有在 video 或 videoGroup 类型时才设置 warn 和 channelId
            if (isVideoOrVideoGroupType(data)) {
                log.info("设置warn和channelId");
                push.getPushNotify().getAndroidNotify().setWarn("12");
                push.getPushNotify().getAndroidNotify().setAndroidChannelId("PHONE_CALL");
            }
            // Android
            if (this.push.getPushFactoryExtra() == null) {
                this.push.setPushFactoryExtra(PushFactoryExtra.builder().build());
            }

            VivoExtra vivoExtra = VivoExtra.builder().build();
            vivoExtra.setClassification(1);


            //华为厂商推送
            HuaweiExtra huaweiExtra = HuaweiExtra.builder().build();
            huaweiExtra.setImportance("NORMAL");


            XiaomiExtra xiaomiExtra = XiaomiExtra.builder().build();
            xiaomiExtra.setChannelId("130111");

            if (!StringUtils.isEmpty(data)) {
                /*
                {
                    "groupid": "666ac1075239c9453271d2ce",
                    "type": "chatGroupMessage",
                    "message": {
                        "duration": 2,
                        "senderID": "862602014404057",
                        "senderType": 2,
                        "id": "667940b3223022000827dce1",
                        "type": 3
                    }
                }
                {
                    "type": "accountMessage",
                    "message": {
                        "openid": "2c9fd11c8a0be2ad018a0be2adc40000",
                        "type": "video",
                        "video_type": 4,
                        "connection_address": "http:cn.router.justalkcloud.com:8080",
                        "imei": "862602014404057",
                        "call_type": 0
                    }
                }
                */
                JSONObject dataOB = JSONObject.parseObject(data);
                String type = dataOB.getString("type");
                if ("chatGroupMessage".equals(type)) {
                    huaweiExtra.setCategory("IM");
                    vivoExtra.setCategory("IM");
                } else if ("accountMessage".equals(type)) {
                    JSONObject message = dataOB.getJSONObject("message");
                    if (message != null) {
                        String msgType = message.getString("type");
                        if ("video".equals(msgType) || "reject".equals(msgType) || "videoGroup".equals(msgType)) {
                            huaweiExtra.setCategory("VOIP"); //音视频通话
                            vivoExtra.setCategory("IM");
                        } else {
                            huaweiExtra.setCategory("DEVICE_REMINDER"); // 设备提醒
                            vivoExtra.setCategory("DEVICE_REMINDER");
                        }
                    }
                }
            }

            this.push.getPushFactoryExtra().setHuaweiExtra(huaweiExtra);
            this.push.getPushFactoryExtra().setVivoExtra(vivoExtra);
            this.push.getPushFactoryExtra().setXiaomiExtra(xiaomiExtra);
        }
        this.push.getPushForward().setScheme(scheme);
        this.push.getPushForward().setNextType(2);
        //this.push.getPushNotify().setSkipOnline(1);
        if (extraMap != null && extraMap.size() > 0) {
            this.push.getPushForward().setSchemeDataList(getExtraParamsList(extraMap));
        }
        if (StringUtil.isNotBlank(data)) {
            List<PushMap> schemeDataList = new ArrayList<>();
            PushMap pushMap = new PushMap();
            pushMap.setKey("data");
            pushMap.setValue(data);
            schemeDataList.add(pushMap);
            push.getPushForward().setSchemeDataList(schemeDataList);
        }
    }

    /**
     * 检查数据是否为 video 或 videoGroup 类型
     *
     * @param data JSON字符串数据
     * @return 如果是video或videoGroup类型返回true，否则返回false
     */
    private boolean isVideoOrVideoGroupType(String data) {
        if (StringUtils.isEmpty(data)) {
            return false;
        }

        try {
            JSONObject dataOB = JSONObject.parseObject(data);
            if (!"accountMessage".equals(dataOB.getString("type"))) {
                return false;
            }

            JSONObject message = dataOB.getJSONObject("message");
            if (message == null) {
                return false;
            }

            String msgType = message.getString("type");
            return "video".equals(msgType) || "videoGroup".equals(msgType);
        } catch (Exception e) {
            log.error("解析 data 时出错: {}", e.getMessage());
            return false;
        }
    }

    /**
     * @param title
     * @param content
     * @param tag
     * @time: 2020/11/28 17:00
     * @author: Rock
     * @version 1.0
     */
    /*public MyPushWorkBuilder setTargetTag(String content, String scheme, String data, Integer platfrom, Integer iosProduction,
                                          Map<String,String> extraMap, String tag) {
        this.fillParams(content, scheme, data, platfrom, iosProduction, extraMap);
        push.getPushTarget().setTarget(TARGET_TAGS);
        push.getPushTarget().setTags(SetUtil.newSet(tag));
        return this;
    }*/

    /**
     * 别名设置
     *
     * @param content
     * @param scheme
     * @param data
     * @param platfrom
     * @param iosProduction
     * @param extraMap
     * @param alias         别名列表 ["alias1","alias2"]
     * @time: 5/21/22 5:14 PM
     * @author: Weichao
     * @version 1.0
     */
    public MyPushWorkBuilder setTargetByAlias(String content, String scheme, String data, Integer platfrom, Integer iosProduction,
                                              Map<String, String> extraMap, String alias) {
        this.fillParams(content, scheme, data, platfrom, iosProduction, extraMap);
        push.getPushTarget().setTarget(TARGET_ALIAS);
        push.getPushTarget().setAlias(SetUtil.newSet(alias));
        return this;
    }


    /**
     * 推送 registrationId 设置
     *
     * @param content
     * @param scheme
     * @param data
     * @param platfrom
     * @param iosProduction
     * @param extraMap
     * @param rid           设置推送Registration Id集合["id1","id2"]
     * @time: 5/21/22 5:15 PM
     * @author: Weichao
     * @version 1.0
     */
    public MyPushWorkBuilder setTargetByRids(String content, String scheme, String data, Integer platfrom, Integer iosProduction,
                                             Map<String, String> extraMap, String rid) {
        this.fillParams(content, scheme, data, platfrom, iosProduction, extraMap);
        push.getPushTarget().setTarget(TARGET_RIDS);
        push.getPushTarget().setRids(SetUtil.newSet(rid));
        return this;
    }

    /**
     * @param extraMap
     * @time: 2020/11/27 14:31
     * @author: Rock
     * @version 1.0
     */
    public List getExtraParamsList(Map<String, String> extraMap) {
        List<PushMap> pushMapList = new ArrayList<>();
        Iterator<Map.Entry<String, String>> entries = extraMap.entrySet().iterator();
        PushMap pushMap;
        while (entries.hasNext()) {
            Map.Entry<String, String> entry = entries.next();
            pushMap = new PushMap();
            pushMap.setKey(entry.getKey());
            pushMap.setValue(entry.getValue());
            pushMapList.add(pushMap);
        }
        return pushMapList;
    }
}
